package cn.kgc.springboot.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.UUID;

/**
 * @author mosin
 * date 2021/12/17
 * @version 1.0
 */
@Controller
@RequestMapping("/file")
public class FileController {

    @RequestMapping("/upload")
    public String upload(MultipartFile file, Model model){ // 处理文件上传

        //判定是否有文件上传
        if(!file.isEmpty()){
            //获取文件的名字
            String originalFilename = file.getOriginalFilename();
            //生成文件在磁盘中保存的唯一识别符 uuid
            String uuid = UUID.randomUUID().toString().replace("-", "");
            //获取文件的后缀名
            String suffixFileName = originalFilename.substring(originalFilename.lastIndexOf("."));
            //拼接文件在磁盘中存储的名字
            String lastFileName = uuid+suffixFileName;

            //保存文件名字 到model 传递参数到下载页面
            model.addAttribute("realName", originalFilename);
            model.addAttribute("downLoadName", lastFileName);
            File diskPath = new File("D:\\upload\\", lastFileName);

            try {
                file.transferTo(diskPath);
            } catch (IOException e) {
                e.printStackTrace();
            }

        }

        return "download";
    }

    @RequestMapping("/toupload")
    public String toUpload(){
        return "upload";
    }

    @RequestMapping("/download")
    public String downLoad(String fileName, HttpServletResponse response)  {

        File diskPath = new File("D:\\upload\\", fileName);
        try {
            FileInputStream fileInputStream = new FileInputStream(diskPath);
            //设置以附件的形式响应
            response.setHeader("Content-disposition", "attachment; filename="+fileName);
            ServletOutputStream outputStream = response.getOutputStream();
            //实现流的对拷
            FileCopyUtils.copy(fileInputStream, outputStream);
            outputStream.close();
            fileInputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "ok";
    }
}
